import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getReports, exportReports } from '@/api/report'

export const useReportStore = defineStore('report', () => {
  // 状态
  const reports = ref([])
  const total = ref(0)
  const loading = ref(false)
  
  // 获取举报列表
  const fetchReports = async (params) => {
    loading.value = true
    try {
      const res = await getReports(params)
      if (res.code === 200) {
        reports.value = res.data.items || []
        total.value = res.data.total || 0
      } else {
        console.error('获取举报数据失败', res.message)
      }
    } catch (error) {
      console.error('获取举报数据异常', error)
    } finally {
      loading.value = false
    }
    return { reports: reports.value, total: total.value }
  }
  
  // 导出举报列表
  const exportReportsList = async (params) => {
    try {
      const res = await exportReports(params)
      
      // 检查响应是否为空
      if (!res || res.size === 0) {
        throw new Error('导出的文件为空')
      }
      
      // 检查响应类型
      const contentType = res.type
      if (!contentType.includes('spreadsheetml.sheet') && !contentType.includes('ms-excel')) {
        // 如果响应不是Excel文件，尝试读取错误信息
        const text = await res.text()
        throw new Error(text || '导出的文件格式不正确')
      }
      
      // 处理导出文件
      const blob = new Blob([res], { type: contentType })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `举报数据列表_${new Date().toLocaleDateString()}.xlsx`
      document.body.appendChild(link)
      link.click()
      
      // 清理资源
      window.URL.revokeObjectURL(url)
      document.body.removeChild(link)
      
      return true
    } catch (error) {
      console.error('导出举报数据失败', error)
      throw error
    }
  }
  
  return {
    reports,
    total,
    loading,
    fetchReports,
    exportReportsList
  }
})